package com.jj.fly.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.dom4j.DocumentException;

import com.jj.fly.utils.CheckUtils;
import com.jj.fly.utils.LogUtils;
import com.jj.fly.utils.MessageUtils;

/**
 * 测试微信接入servlet
 * 
 * @author JJ
 *
 */
public class WeixinServlet extends HttpServlet {

	private Log logger = LogUtils.getFrameworkLoger();

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String signature = req.getParameter("signature");
		String timestamp = req.getParameter("timestamp");
		String nonce = req.getParameter("nonce");
		String echostr = req.getParameter("echostr");
		boolean result = CheckUtils.checkSignature(signature, timestamp, nonce);
		PrintWriter out = resp.getWriter();
		if (result == true) {
			out.print(echostr);
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		resp.setCharacterEncoding("UTF-8");
		PrintWriter out = resp.getWriter();
		try {
			Map<String, String> map = MessageUtils.xmlToMap(req);
			String toUserName = map.get("ToUserName");
			String fromUserName = map.get("FromUserName");
			String msgType = map.get("MsgType");
			String content = map.get("Content");
			String message = null;
			if (msgType.equals(MessageUtils.MESSAGE_TEXT)) {
				// 文本消息
				if ("1".equals(content)) {
					message = MessageUtils.initText(toUserName, fromUserName,
							MessageUtils.firstMenu());
				} else if ("2".equals(content)) {
					message = MessageUtils.initNewsMessage(toUserName,
							fromUserName);
				} else if ("?".equals(content) || "？".equals(content)) {
					message = MessageUtils.initText(toUserName, fromUserName,
							MessageUtils.menuText());
				}
				logger.info(message);
			} else if (msgType.equals(MessageUtils.MESSAGE_EVENT)) {
				// 事件推送
				String eventType = map.get("Event");
				if (eventType.equals(MessageUtils.MESSAGE_SUBSCRIBE)) {
					message = MessageUtils.initText(toUserName, fromUserName,
							MessageUtils.menuText());
				} else if (eventType.equals(MessageUtils.MESSAGE_UNSUBSCRIBE)) {

				}
			}
			out.print(message);
		} catch (DocumentException e) {
			logger.error(e);
			e.printStackTrace();
		} finally {
			out.close();
		}
	}
}
